package com.chap6;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;

/**
 * <p>
 * <code>CountDownLatchDemo2</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-20 5:15
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class CountDownLatchDemo2 {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            final int index = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000+ ThreadLocalRandom.current().nextInt(2000));
                        System.out.println("任务"+index+"执行完成");
                        countDownLatch.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }).start();

        }
        countDownLatch.await();
        System.out.println("主线程：在所有任务运行完成后，进行结果汇总");
    }
}
